package com.hunantv.mglive.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.hunantv.mglive.common.MaxApplication;

/**
 * qiansong
 */
public class DeviceInfoUtil {
    private static final int BUFFER_SIZE = 1024;
    private static final String TAG = "DeviceInfo";
    private static int width;
    private static int height;

    /**
     * 获取versioncode
     *
     * @param context
     * @return
     * @throws JSONException
     */
    public static int getVersionCode(Context context) {
        int versionCode = -1;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return versionCode;
    }

    /**
     * 获取versionName
     *
     * @param context
     * @return
     * @throws JSONException
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return versionName;
    }

    /**
     * 获取Cpu利用信息
     *
     * @return
     */
    public static int getCpuUsedMsg() {
        String Result;
        try {
            Process p = Runtime.getRuntime().exec("top -n 1");

            BufferedReader br = new BufferedReader(new InputStreamReader
                    (p.getInputStream()));
            while ((Result = br.readLine()) != null) {
                if (Result.trim().length() < 1) {
                    continue;
                } else {
                    String[] CPUusr = Result.split("%");
                    String[] CPUusage = CPUusr[0].split("User");
                    String[] SYSusage = CPUusr[1].split("System");

                    try {
                        int userUse = Integer.parseInt(CPUusage[1].trim());
                        int sysUse = Integer.parseInt(SYSusage[1].trim());
                        return userUse + sysUse;
                    }catch (NumberFormatException e){

                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 获取分辨率
     *
     * @param context
     * @throws JSONException
     */
    public static String getResolution(Context context) {
        String resolution = "";
        try {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            window.getDefaultDisplay().getMetrics(metrics);
            int width = metrics.widthPixels;
            int height = metrics.heightPixels;
            int temp;
            if (width > height) {
                temp = width;
                width = height;
                height = temp;
            }
            resolution = String.valueOf(width) + "," + String.valueOf(height);
        } catch (Exception e2) {
            L.e(TAG, e2);

        }
        return resolution;
    }

    /**
     * 获取分辨率
     *
     * @param context
     * @throws JSONException
     */
    public static String getResolution2(Context context) {
        String resolution = "";
        try {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            window.getDefaultDisplay().getMetrics(metrics);
            int width = metrics.widthPixels;
            int height = metrics.heightPixels;
            int temp;
            if (width > height) {
                temp = width;
                width = height;
                height = temp;
            }
            resolution = String.valueOf(width) + "*" + String.valueOf(height);
        } catch (Exception e2) {
            L.e(TAG, e2);

        }
        return resolution;
    }

    /**
     * 获取分辨率
     *
     * @param context
     * @throws JSONException
     */
    public static int getResolutionWidth(Context context) {
        if (width >= 0) {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            window.getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
            int temp;
            if (width > height) {
                temp = width;
                width = height;
                height = temp;
            }
        }
        return width;
    }

    /**
     * 获取分辨率
     *
     * @param context
     * @throws JSONException
     */
    public static int getResolutionHeight(Context context) {
        if (width >= 0) {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            window.getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
            int temp;
            if (width > height) {
                temp = width;
                width = height;
                height = temp;
            }
        }
        return height;
    }

    // private static void getLocalInfo(Context context, JSONObject result)
    // throws JSONException {
    // Configuration config = new Configuration();
    // Settings.System.getConfiguration(context.getContentResolver(), config);
    // TimeZone timeZone;
    // if ((config != null) && (config.locale != null)) {
    // result.put("Country", config.locale.getCountry());
    // result.put("Language", config.locale.toString());
    // Calendar calendar = Calendar.getInstance(config.locale);
    // if (calendar != null) {
    // timeZone = calendar.getTimeZone();
    // if (timeZone != null) {
    // result.put(LogConstants.TIME_ZONE, timeZone.getRawOffset() /
    // HOUR_TO_MILLS_UNIT);
    // } else {
    // result.put(LogConstants.TIME_ZONE, LogConstants.DEFAULT_TIME_ZONE);
    // }
    // } else {
    // result.put(LogConstants.TIME_ZONE, LogConstants.DEFAULT_TIME_ZONE);
    // }
    // } else {
    // Locale local = Locale.getDefault();
    // String country = local.getCountry();
    // if (!TextUtils.isEmpty((CharSequence) country)) {
    // result.put(LogConstants.COUNTRY, country);
    // } else {
    // result.put(LogConstants.COUNTRY, LogConstants.UNKNOWN);
    // }
    // String language = local.getLanguage();
    // if (!TextUtils.isEmpty(language)) {
    // result.put(LogConstants.LANGUAGE, language);
    // } else {
    // result.put(LogConstants.LANGUAGE, LogConstants.UNKNOWN);
    // }
    // Calendar calendar = Calendar.getInstance(local);
    // if (calendar != null) {
    // timeZone = calendar.getTimeZone();
    // if (timeZone != null) {
    // result.put(LogConstants.TIME_ZONE, ((TimeZone) timeZone).getRawOffset() /
    // HOUR_TO_MILLS_UNIT);
    // } else {
    // result.put(LogConstants.TIME_ZONE, LogConstants.DEFAULT_TIME_ZONE);
    // }
    // } else {
    // result.put(LogConstants.TIME_ZONE, LogConstants.DEFAULT_TIME_ZONE);
    // }
    // }
    // }

    /**
     * @return cpu info
     */
    public static String getCupInfo() {
        String str = null;
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader("/proc/cpuinfo");
            if (fileReader != null) {
                try {
                    bufferedReader = new BufferedReader(fileReader, BUFFER_SIZE);
                    str = bufferedReader.readLine();
                    bufferedReader.close();
                    fileReader.close();
                } catch (IOException ex) {
                    L.d(TAG, "读CPU信息失败");
                }
            }
        } catch (FileNotFoundException fileEx) {
            L.d(TAG, "读CPU信息失败");
        }

        return str.trim();
    }

    // /**
    // * @param context
    // * 上下文
    // * @return 可用网络
    // */
    // public static String[] getNetwork(Context context) {
    // String[] arrayOfString = { LogConstants.UNKNOWN, LogConstants.UNKNOWN };
    // PackageManager packageManager = context.getPackageManager();
    // if
    // (packageManager.checkPermission("android.permission.ACCESS_NETWORK_STATE",
    // context.getPackageName()) != 0) {
    // arrayOfString[0] = LogConstants.UNKNOWN;
    // return arrayOfString;
    // }
    // ConnectivityManager conManager = (ConnectivityManager)
    // context.getSystemService("connectivity");
    // if (conManager == null) {
    // arrayOfString[0] = LogConstants.UNKNOWN;
    // return arrayOfString;
    // }
    // NetworkInfo networkInfo = conManager.getNetworkInfo(1);
    // if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
    // arrayOfString[0] = "Wi-Fi";
    // return arrayOfString;
    // }
    // NetworkInfo otherNetworkInfo = conManager.getNetworkInfo(0);
    // if (otherNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
    // arrayOfString[0] = LogConstants.GSM;
    // arrayOfString[1] = otherNetworkInfo.getSubtypeName();
    // return arrayOfString;
    // }
    // return arrayOfString;
    // }

    /**
     * @param context 上下文
     * @return 设备ID
     */
    public static String getDeviceId(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = "";
        try {
            if (PackageUtil.checkPermission(context, "android.permission.READ_PHONE_STATE")) {
                deviceId = telephonyManager.getDeviceId();
            }
        } catch (Exception ex) {
            L.e(TAG, ex);
        }
        if (TextUtils.isEmpty(deviceId)) {
            L.d(TAG, "No IMEI.");
            deviceId = getMacAddress(context);
            if (deviceId == null) {
                L.e(TAG, "Failed to take mac as IMEI.");
            }
        }
        if (StringUtil.isNullorEmpty(deviceId)) {
            deviceId = getUniquePsuedoID();
        }
        if (StringUtil.isNullorEmpty(deviceId)) {
            deviceId = "unknown";
        }
        return deviceId;
    }

    public static String getUniquePsuedoID() {
        String serial;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * @param paramContext paramContext
     * @return String
     * @throws
     * @Method: getMacAddress
     */
    public static String getMacAddress(Context paramContext) {
        String result = null;
        try {
            WifiManager wifiManager = (WifiManager) paramContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            result = wifiInfo.getMacAddress();
        } catch (Exception ex) {
            L.d(TAG, "不能读mac地址");
        }
        return result;
    }

    //0=iOS 1=android
    public static String getOSType() {
        return "1";
    }

    public static String getEndType() {
        return "phone";
    }

    public static String getDevice() {
        return android.os.Build.MODEL;
    }

    public static String getManufacturer() {
        return android.os.Build.MANUFACTURER;
    }

    //个推的id
    public static String getCid() {
        return MaxApplication.getInstance().getClientId();
    }

    public static String getOSVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @param context
     * @return 平板返回 True，手机返回 False
     */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static String getSimOperatorInfo(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operatorString = telephonyManager.getSimOperator();
        if (operatorString == null) {
            return "00";
        }
        if (operatorString.equals("46000") || operatorString.equals("46002")) {
            //中国移动
            return "00";
        } else if (operatorString.equals("46001")) {
            //中国联通
            return "01";
        } else if (operatorString.equals("46003")) {
            //中国电信
            return "03";
        }
        //error
        return "00";
    }

    public static String getSimCountryMCC(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operatorString = telephonyManager.getSimOperator();
        if (operatorString != null && operatorString.length() > 3) {
            return operatorString.substring(0, 3);
        }
        return "";
    }

    public static int getNetWork(Context context) {
        NetworkUtils.NetType netType = NetworkUtils.getNetworkTypeInternal(context);
        if (netType.equals(NetworkUtils.NetType.Wifi)) {
            //wifi
            return 0;
        } else if (netType.equals(NetworkUtils.NetType.G2) || netType.equals(NetworkUtils.NetType.G3) || netType.equals(NetworkUtils.NetType.G4) || netType.equals(NetworkUtils.NetType.Cable)) {
            //手机
            return 1;
        } else {
            //无网络
            return 2;
        }
    }


    /**
     * 获取APP所占内存
     * @return 内存大小MB
     */
    public static int getAppMemory(Context mContext) {
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        android.os.Debug.MemoryInfo[] processMemoryInfo
                = activityManager.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
        android.os.Debug.MemoryInfo memoryInfo = processMemoryInfo[0];
        int totalPrivateDirty = memoryInfo.getTotalPrivateDirty()/1024; //MB
        return totalPrivateDirty;

    }

    /**
     * 获取设备可用内存
     * @return 可用内存大小MB
     */
    public static long getAvailMemory(Context mContext){
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem/1024;
    }
}
